<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    String point=(String) request.getSession().getAttribute("coordinatePoint");
%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>城市地图</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=10,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=0.3, user-scalable=0, minimum-scale=0, maximum-scale=5.0,user-scalable=yes">

    <link rel="stylesheet" type="text/css" href="/css/street/street.css"/>
    <link rel="stylesheet" href="/css/officialDocument/officialDocument.css">
    <style>
        .formUl li label {
            float: left;
            width: 150px;
            vertical-align: middle;
            height: 34px;
            line-height: 34px;
            text-align: right;
            font-size: 14px;
        }
        .formUl li input[type=text]{
            border:1px solid #ddd;
        }
    </style>
    <script src="/js/jquery/jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
    <script src="/lib/layer/layer.js?20201106" type="text/javascript" charset="utf-8"></script>
    <script src="/js/base/base.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=YECw4heQ9wzy7RKg8OW9QLMsySKzQRan"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
    <!--加载检索信息窗口-->
    <script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
    <style>
        .btnArr span,.editBtn{
            font-size: 14px;
            padding:5px 14px;
            border-radius:6px;
            background: #0090e3;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>
<body >
<div style="margin-left:50px;float: left;margin-top:20px;width: 100%">
    <input type="text" id="suggestId" size="20" value="" style="width:200px;margin-bottom: 10px;height:28px;border-radius: 3px;border:1px solid #e2e3e3;"
           placeholder="请输入地址检索"/>
    <a href="javascript:void(0);" onclick="document.getElementById('suggestId').value=''" style="font-size: 14px;
    padding: 5px 14px;
    border-radius: 6px;
    background: #0090e3;
    color: #fff;
    cursor: pointer;">清除</a>
    <div style="float: right;margin-right: 70px">
        <button class="editBtn"  onclick = "poy.enableEditing();">开启线、面编辑功能</button>
        <button class="editBtn"  onclick = "poy.disableEditing();">关闭线、面编辑功能</button>
    </div>

</div>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>

    <div class="mainRight" id="allmap" style="height: 600px;width: 100%;float: none">

    </div>
    <div class="btnArr" style="width: 100%;height: 55px;line-height: 55px;text-align: center">
        <span class="mapSave" style="margin-right: 10px">
            保存
        </span>
        <span class="mapClear" onclick="clearAll()">
            清除
        </span>
    </div>
    <%--<button onclick = "scopeOfTheCommunity.polygon.enableEditing();">开启线、面编辑功能</button>--%>
    <%--<button onclick = "scopeOfTheCommunity.polygon.disableEditing();">关闭线、面编辑功能</button>--%>
    <%--<button onclick = "scopeOfTheCommunity.inits();">坐标显示</button>--%>


<script type="text/javascript">

     function allPoint() {
         overlays='';
         // console.log(poy.getPath())
         if(poy!=undefined){
             var allOverlay = poy.getPath();
             for(var i=0;i<allOverlay.length;i++){
                 overlays += allOverlay[i].lng +','+ allOverlay[i].lat +'|'
             }
         }else{
             if(overlaysTwo.length >0){
                 var allOverlay = overlaysTwo[0].ia;
                 for(var i=0;i<allOverlay.length;i++){
                     overlays+=allOverlay[i].lng +','+ allOverlay[i].lat +'|'
                 }
             }

             // var allOverlay = maps.map.getOverlays();
             //
             // for (var i = 0; i < allOverlay.length ; i++) {
             //
             //     if (allOverlay[i].toString() == "[object Polygon]") {
             //
             //         for (var num = 0; num < allOverlay[i].getPath().length; num++) {
             //
             //             if (num != allOverlay[i].getPath().length - 1) {
             //                 overlays += allOverlay[i].getPath()[num].lng +','+ allOverlay[i].getPath()[num].lat +'|'
             //             }
             //             else {
             //                 overlays += allOverlay[i].getPath()[num].lng + ',' + allOverlay[i].getPath()[num].lat
             //             }
             //
             //         }
             //         // mypoints = "{points:[" + overlays + "]}";
             //         // alert(mypoints);
             //     }
             // }
         }
         // console.log(overlays)

     }

    var label;
    function mouseoveTwo(e) {

        if(label!=undefined){
            maps.map.removeOverlay(label)
        }
        // console.log(e)
        var point = new BMap.Point(e.point.lng,e.point.lat);

        var opts = {
            position : point    // 指定文本标注所在的地理位置
        }
        label = new BMap.Label(e.target.strData, opts);  // 创建文本标注对象
        label.setStyle({
            color : "red",
            fontSize : "12px",
            height : "20px",
            lineHeight : "20px",
            fontFamily:"微软雅黑"
        });
        maps.map.addOverlay(label);

//            layer.tips(e.target.strData, e.target, {guide: 1, time: 2});
    }

    var scopeOfTheCommunity={
        polygon:null,
        init:function (dataArr,num,ids,type,strData,sheqvObj) {
            var colors='red';

            this.polygon=new BMap.Polygon(dataArr, {strokeColor:colors, strokeWeight:2, strokeOpacity:1, fillOpacity: 0.05});  //创建多边形
//                var strIng=strData;
            this.polygon.addEventListener("mouseover",mouseoveTwo,false);

            this.polygon.objData=ids;
            this.polygon.strData=strData;

            maps.map.addOverlay(this.polygon);   //增加多边形


        },
        inits:function () {
            // console.log(this.polygon.ia)
        }
    }
    var obj=$.GetRequest();
    var overlays = [];
    var mapstr='';
    var str='';
    var overlaysTwo=[];
    var markerArr=[];
    $('.mainRight').height($(document).height()-105);





    var overlaycomplete = function(e){
        // console.log(e.drawingMode);
//       console.log(e.overlay.ia)
        if(e.drawingMode=='polygon') {
            var arr = e.overlay.ia;
            arr.pop();
           // console.log(arr)
            if(overlays.length<1) {
                for (var i = 0; i < arr.length; i++) {
                    if (i < arr.length - 1) {
                        mapstr += arr[i].lng + ',' + arr[i].lat + '|'
                    } else {
                        mapstr += arr[i].lng + ',' + arr[i].lat
                    }
                }
            }

            for (var i = 0; i < arr.length; i++) {
                if (i < arr.length - 1) {
                    str += arr[i].lng + ',' + arr[i].lat + '|'
                } else {
                    str += arr[i].lng + ',' + arr[i].lat
                }
            }
            overlays.push(str);
            str='';
            overlaysTwo.push(e.overlay);
            // console.log(overlaysTwo);
        }

        if(e.drawingMode=='marker'){
           if(markerArr.length>0) {
               for(var i = 0; i < markerArr.length; i++){
                   maps.map.removeOverlay(markerArr[i]);
               }
               markerArr.length = 0;
               markerArr.push(e.overlay);
           }else {
               markerArr.push(e.overlay);
           }

        }
        // console.log(markerArr);
    };

    var styleOptions = {
        strokeColor:"red",    //边线颜色。
        fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }
    var maps={
        map:null,
        point:null,
        init:function (fn) {
            this.map = new BMap.Map("allmap",{mapType:BMAP_ANCHOR_TOP_LEFT});// 创建Map实例
           // this.point = new BMap.Point(116.666549,40.11856);//设置坐标
            this.point = new BMap.Point(<%=point%>);
            this.map.centerAndZoom(this.point, 16);//创建比例
            this.map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
            this.map.setCurrentCity("北京");// 设置地图显示的城市 此项是必须设置的
            this.map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放

//            $.get('/gridInfo/selectByPrimaryKey',{gridInfo:window.opener.document.getElementsByClassName('gridIds')[0].value},function (json) {
//                if(json.flag) {
//                    var jsonobj=json.data;
//                    if(jsonobj.mapInfo.indexOf('&')==-1){
//                        var chiArr = jsonobj.mapInfo.split('|');
//                        var newArr = [];
//                        for (var m = 0; m < chiArr.length; m++) {
//                            newArr.push(new BMap.Point(parseFloat(chiArr[m].split(',')[0]), parseFloat(chiArr[m].split(',')[1])))
//                        }
//                        scopeOfTheCommunity.init(newArr, 2, jsonobj.gridId, 2, jsonobj.gridName)
//
//                    }else {
//                        var chiArr = jsonobj.mapInfo.split('&');
//                        for(var m=0;m<chiArr.length;m++){
//                            var chiTwoArr=chiArr[m].split('|');
//                            var newArrTwo= [];
//                            for(var k=0;k<chiTwoArr.length;k++){
//                                newArrTwo.push(new BMap.Point(parseFloat(chiTwoArr[k].split(',')[0]), parseFloat(chiTwoArr[k].split(',')[1])))
//                            }
//                            scopeOfTheCommunity.init(newArrTwo, 2, jsonobj.gridId, 2, jsonobj.gridName)
//                        }
//                    }
//                    $.get('/gridInfo/gridSettingsTreeUpAndDown',{typeId:window.opener.document.getElementsByClassName('gridIds')[0].value},function (json) {
//                        if(json.flag){
//                            var jsonArr=json.obj;
//                            for(var i=0;i<jsonArr.length;i++){
//                                var chistr=jsonArr[i].mapInfo;
//                                if(chistr.indexOf('&')==-1) {
//                                    var chiArr = jsonArr[i].mapInfo.split('|');
//                                    var newArr = [];
//                                    for (var m = 0; m < chiArr.length; m++) {
//                                        newArr.push(new BMap.Point(parseFloat(chiArr[m].split(',')[0]), parseFloat(chiArr[m].split(',')[1])))
//                                    }
//
//
//
//
//                                    if(jsonArr[i].gridInfoDivsive==3){//网格
//
//                                            scopeOfTheCommunity.init(newArr, 2, jsonArr[i].gridId, 2, jsonArr[i].gridName)
//
//                                    }else if(jsonArr[i].gridInfoDivsive==1){//街道
//                                        scopeOfTheCommunity.init(newArr,1,jsonArr[i].gridId,2,jsonArr[i].gridName)
//                                    }else if(jsonArr[i].gridInfoDivsive==2){//社区
//
//                                        scopeOfTheCommunity.init(newArr,3,jsonArr[i].gridId,2,jsonArr[i].gridName,jsonArr[i])
//
//                                    }
//                                }else if(chistr.indexOf('&')!=-1){
//                                    var chiArr = jsonArr[i].mapInfo.split('&');
//
//                                    for(var m=0;m<chiArr.length;m++){
//                                        var chiTwoArr=chiArr[m].split('|');
//                                        var newArrTwo= [];
//                                        for(var k=0;k<chiTwoArr.length;k++){
//                                            newArrTwo.push(new BMap.Point(parseFloat(chiTwoArr[k].split(',')[0]), parseFloat(chiTwoArr[k].split(',')[1])))
//                                        }
//
//                                        if(jsonArr[i].gridInfoDivsive==3){//网格
//
//                                                scopeOfTheCommunity.init(newArrTwo, 2, jsonArr[i].gridId, 2, jsonArr[i].gridName)
//
//                                        }else if(jsonArr[i].gridInfoDivsive==1){//街道
//                                            scopeOfTheCommunity.init(newArrTwo,1,jsonArr[i].gridId,2,jsonArr[i].gridName)
//                                        }else if(jsonArr[i].gridInfoDivsive==2){//社区
//
//                                            scopeOfTheCommunity.init(newArrTwo,3,jsonArr[i].gridId,2,jsonArr[i].gridName,jsonArr[i])
//
//                                        }
////                                scopeOfTheCommunity.init(newArrTwo, 2,jsonArr[i].gridId,1,jsonArr[i].gridName)
//
//                                    }
//                                }
//                            }
//                        }
//                    },'json')
//
//                }
//            },'json')

            if(fn!=undefined){
                fn()
            }
        }
    }

    function clearAll() {

        // maps.map.removeOverlay(poy)

        if(poy!=undefined){
            for(var i = 0; i < overlaysTwo.length; i++){
                maps.map.removeOverlay(overlaysTwo[i]);
            }
            overlaysTwo.length = 0;
            overlays.splice(0,overlays.length);
            mapstr='';
            str='';
            maps.map.removeOverlay(poy)
            poy = undefined
        }else{
            for(var i = 0; i < overlaysTwo.length; i++){
                maps.map.removeOverlay(overlaysTwo[i]);
            }
            overlaysTwo.length = 0;
            overlays.splice(0,overlays.length);
            mapstr='';
            str='';
            maps.map.clearOverlays();
        }


    }


    maps.init(function () {
        var drawingManagerConfig={};
        var drawingManager = new BMapLib.DrawingManager(maps.map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
            },
            circleOptions: styleOptions, //圆的样式
            polylineOptions: styleOptions, //线的样式
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions //矩形的样式
        });
        drawingManager.addEventListener('overlaycomplete', overlaycomplete);

//        搜索
        function G(id) {
            return document.getElementById(id);
        }
        var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
            {
                "input": "suggestId"
                , "location": allmap
            });
        ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if (e.fromitem.index > -1) {
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            G("searchResultPanel").innerHTML = str;
        });
        var myValue;
        ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
            G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

            setPlace();
        });
        function setPlace() {
            maps.map.clearOverlays();    //清除地图上所有覆盖物
            function myFun() {
                var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                maps.map.centerAndZoom(pp, 18);
               // maps.map.addOverlay(new BMap.Marker(pp));    //添加标注

//                markerArr.push({point:pp})
            }

            var local = new BMap.LocalSearch(maps.map, { //智能搜索
                onSearchComplete: myFun
            });
            local.search(myValue);

        }
    })

    if( obj.dataType == 'wangge' ||  obj.dataType == 'sheqv'){
        var wg= window.opener.sendEcho();
        var arr=[];
        if(wg != ''){
            arr=wg.split('|');
            var poy = new BMap.Polygon(function(){
                var arr2=[];
                for(var i=0;i<arr.length;i++){
                    var type =arr[i].split(',')
                    if(!isNaN(type[0])&&type[0]!=0&&type[1]!=0&&!isNaN(type[1])){
                        var no=new BMap.Point(type[0],type[1]);
                        arr2.push(no);
                    }

                }
//                            console.log(arr2)
                return arr2;
            }(), {strokeColor:'#000',fillColor:'red', fillOpacity: 0.3,  strokeWeight:1, strokeOpacity:0.5});  //创建多边形
            maps.map.addOverlay(poy);
            // console.log(poy)

        }
    }




    $('.mapSave').click(function () {
         allPoint();
         // console.log(overlays)
        if(obj.type==1){
            if(overlays.length==0){
                alert('请先画出网格范围，再保存');
                return;
            }
            if(obj.dataType=='sheqv'){
                if(overlays.length==1){
                    window.opener.theEcho(mapstr)
                    window.close();
                }else {
                    alert('只能选择一个范围区域');
                }
            }else if(obj.dataType=='wangge'){
                // console.log(overlays)
                if(overlays.length==1){
                    window.opener.theEcho(mapstr)
                    window.close();
                }else if(overlays.length>1){
                    if (typeof overlays=='string')
                    {
                        var mapstrs=overlays;
                    }
                    else {
                        var mapstrs=overlays.join('&');
                    }

                    window.opener.theEcho(mapstrs);
                    window.close();
                }
            }





        }else if(obj.type==2){
            if(markerArr.length==0){
                alert('请选择正确工具获取坐标点，进行保存');
                return;
            }
            var markerStr=markerArr[0].point.lng+','+markerArr[0].point.lat;
//            var mapstrs=overlays.join('&');
            window.opener.theEchozuobiao(markerStr)
            window.close();
        }else if(obj.type==3){
            if(markerArr.length==0){
                alert('请选择正确工具获取坐标点，进行保存');
                return;
            }
            var markerStr=markerArr[0].point.lng+','+markerArr[0].point.lat;
//            var mapstrs=overlays.join('&');
            window.opener.theEchozuobiaos(markerStr)
            window.close();
        }else if(obj.type == 4){
            if(markerArr.length==0){
                alert('请选择正确工具获取坐标点，进行保存');
                return;
            }
            var markerStr=markerArr[0].point.lng+','+markerArr[0].point.lat;
//            var mapstrs=overlays.join('&');
            window.opener.setZuobiao(markerStr)
            window.close();
        }
    })


    //    绘制自定义覆盖物
    //    //        1\定义构造函数
    function ComplexCustomOverlay(point,img,name,id,con,grid,type,title){
        this._point = point;
        this._img = img;
        this._name = name;
        this._id = id;
        this._con = con;
        this._grid = grid;
        this._type = type;
        this._title = title;
    }




$(  function () {
    $.ajax({
        url:'/gridInfo/gridSettingsList',
        data:{griti:0},
        dataType:'json',
        success:function(res){
            var data = res.datas;
            var yanse=''
            for(var j=0;j<data.length;j++){
                if(data[j].upperGrid == 1){
                    yanse = 'red'
                }else if(data[j].upperGrid == 2){
                    yanse = 'blue'
                }else{
                    yanse = 'blue'
                }

                var mapInfo = res.datas[j].mapInfo;
                var mapInfoFlag = res.datas[j].mapInfoFlag;

                if(mapInfo != undefined){
                    var arr = mapInfo.split('|');
                    var polygon = new BMap.Polygon(function(){
                        var arr2=[];
                        for(var i=0;i<arr.length;i++){
                            var type =arr[i].split(',')
                            var no=new BMap.Point(type[0],type[1]);
                            arr2.push(no)
                        }
                        return arr2;
                    }(), {strokeColor:yanse,fillColor:'blue', fillOpacity: 0.2,  strokeWeight:2, strokeOpacity:0.5});  //创建多边形
                    maps.map.addOverlay(polygon);

                }
            }
        }
    })
})

</script>
</body>
</html>